package com.tom.netty;

import com.tom.websocket.ChatServerInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * netty 服务器，用于构建和启动当前服务
 *
 * @author zx
 * @date 2024年10月15日 15:03
 */
public class ChatNettyServer {
    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup bossGroup = null;
        EventLoopGroup workGroup = null;
        try {
            //定义主从线程组
            //定义主线程组，用于接收客户端链接,但是不做任何处理
            bossGroup = new NioEventLoopGroup();
            //定义从线程组,用于处理主线程组丢过来的任务
            workGroup = new NioEventLoopGroup();

            // 创建netty 服务器
            //定义启动类
            ServerBootstrap server = new ServerBootstrap();
            //绑定主从线程组
            server.group(bossGroup, workGroup)
                    //设置nio 双向通道
                    .channel(NioServerSocketChannel.class)
                    //处理用户请求的handel ,也就是workGroup
                    //.childHandler(new HttpServerInitializer());
                    .childHandler(new ChatServerInitializer());

            //启动server,绑定端口号，使用同步方式启动
            ChannelFuture channelFuture = server.bind(875)
                    .sync();//使用同步启动

            //监听关闭的channel
            channelFuture.channel().closeFuture().sync();
        } finally {
            if (bossGroup != null) {
                bossGroup.shutdownGracefully();
            }

            if (workGroup != null) {
                workGroup.shutdownGracefully();
            }

        }


    }
}
